
// apicloud官方的模块，有瑕疵（android下出现过，明明有权限，却取不到数据的情况）。已不用，用自己实现的模块，见 uploadContacts2.js
function uploadContacts_old() {
    if (window.uploading) {
        return; // 防止重复提交
    }

    // utils.loading('正在识别中', '请保持网络畅通');
    window.uploading = true;

    // https://docs.apicloud.com/Client-API/Device-Access/contacts#n1
    var mod = api.require("contacts");

    var onFail = function() {
        // utils.rmLoading();
        window.uploading = false;

        if (window.uploadTimer) {
            clearTimeout(window.uploadTimer);
            window.uploadTimer = undefined;
        }

        utils.uploadEvent({event: 'upload-address-book-failed'});

        var msg = '';
        if (isIOS()) {
            msg = '您关闭了通讯录访问。若想继续访问通讯录，请按下面步骤打开。设置-隐私-通讯录-阅同城';
        } else {
            msg = '您关闭了通讯录访问。若想继续访问通讯录，请到设置中的权限管理菜单，打开访问权限';
        }
        apix.alert({title: '获取授权', msg: msg});
    }

    window.uploadTimer = setTimeout(onFail, 15*1000);

    var cb = {
        succ: function(ret) {
            if (ret.total > 0) {
                clearTimeout(window.uploadTimer);
                window.uploadTimer = undefined;

                var data = {data: asJson(ret.contacts)};
                std_ajax_post('wuchen/uploadaddressbook.php', data, {
                    always: function() {
                        // utils.rmLoading();
                        window.uploading = false;
                    },
                    succ: function(json) {
                        evt.send('on-contacts-uploaded', {});
                        // utils.toast('识别完成');
                    },
                    fail: function(err, url) {
                        utils.postErrNoTipsEx(err, url, data);
                    }
                });
            } else {
                onFail();
            }
        },
        fail: function(err) {
            onFail();
        }
    };

    if (isIOS()) {
        getAll(mod, cb);
    } else {
        getAll2(mod, cb);
    }
}

function getAll(mod, cb) {
    // allContacts仅适用于 ios高版本，还不确定。故先尝试，失败后再用queryByPage
    mod.allContacts({}, function(ret, err) {
        wlog("contacts.allContacts() ret: " + asJson(ret) + ', err: ' + asJson(err));
        if (ret && ret.status && ret.total > 0) {
            cb && safeFn(cb.succ)(ret);
        } else {
            getAll2(mod, cb);
        }
    });
}

function getAll2(mod, cb) {
    mod.queryByPage({}, function(ret, err) {
        wlog("contacts.queryByPage() ret: " + asJson(ret) + ', err: ' + asJson(err));
        if (ret && ret.status) {
            cb && safeFn(cb.succ)(ret);
        } else {
            cb && safeFn(cb.fail)(err);
        }
    });
}
